package com.sina.rd.dsp.master;

import com.sina.rd.dsp.protobuf.generated.ServerProtos;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;


/**
 * Created with IntelliJ IDEA.
 * User: xinrong3
 * Date: 14-4-3
 * Time: 下午2:25
 */
public class MasterServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    public static final Log LOG = LogFactory.getLog(MasterServerChannelInitializer.class);

    private final Properties properties;

    public MasterServerChannelInitializer(Properties properties){
        this.properties=properties;
    }


    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        EventExecutorGroup group = new DefaultEventExecutorGroup(30);
        ChannelPipeline p = ch.pipeline();
        p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        p.addLast("protobufDecoder", new ProtobufDecoder( ServerProtos.ReqMessage.getDefaultInstance()));

        p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        p.addLast("protobufEncoder", new ProtobufEncoder());

        p.addLast(group, new MasterServerHandler(properties));
    }
}
